package com.kgd.news;

import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.log.Log4jLogFactory;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlReporter;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.template.Engine;
import com.kgd.news.controller.IndexController;
import com.kgd.news.entity._MappingKit;
import com.kgd.news.ibeetl.func.*;
import com.kgd.news.ibeetl.tag.DictTag;
import com.kgd.news.ibeetl.tag.OneToManyDisplayTag;
import com.kgd.news.route.AdminRoute;
import com.kgd.news.utils.PermissionHandler;
import com.kgd.news.utils.cache.CacheUtils;
import com.kgd.news.utils.ehcache.EhCacheProvider;
import com.kgd.news.utils.quartz.FormaterCronExpression;
import com.kgd.news.utils.quartz.JobBean;
import com.kgd.news.utils.quartz.QuartzPlugin;
import com.kgd.news.utils.wx.VideoHelper;
import com.kgd.news.utils.wx.WxHelper;
import com.kgd.news.wxpay.controller.WxPayController;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.jfinal3.JFinal3BeetlRenderFactory;

import java.util.List;


/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/9/24
 * @Time: 下午4:08
 */
public class NewsApp extends JFinalConfig {
    private final static Log log = Log.getLog(NewsApp.class);

    @Override
    public void configConstant(Constants me) {
        me.setDevMode(true);
//        me.setLogFactory(new Log4jLogFactory());
        me.setEncoding("utf-8");
        me.setViewType(ViewType.JSP);
        PropKit.use("config.txt");
        //        设置文件上传基础路径，该路径参数接受以”/”打头或者以 windows 磁盘盘符打头的绝对路径admin/upload/
//        me.setBaseUploadPath("c:\\news\\upload\\");
        // 开启日志JFinal SqlReporter是个jdk动态代理的东西，拦截prepareStatement，打出sql参数。
//        SqlReporter.setLog(true);
        try {
            // 加载少量必要配置，随后可用PropKit.get(...)获取值
            Configuration.TEMPLATE_ROOT = "/admin/";
            JFinal3BeetlRenderFactory jFinal3BeetlRenderFactory = new JFinal3BeetlRenderFactory();
            jFinal3BeetlRenderFactory.config();
            //集成beet模板到jfinaltemplate.binding
            GroupTemplate gt = jFinal3BeetlRenderFactory.groupTemplate;
            gt.registerTag("dictTag", DictTag.class);
            //gt.registerTag("roleTag", RoleTag.class);
            //gt.registerTag("menuTag", MenuTag.class);
            gt.registerTag("oneToManyTag", OneToManyDisplayTag.class);
            //根据gt可以添加扩展函数，格式化函数，共享变量等，
            gt.registerFunction("dictFunc", new DictFunc());
            //gt.registerFunction("roleFunc", new RoleFunc());
            // gt.registerFunction("menuFunc", new MenuFunc());
            gt.registerFunction("oneToManyFunc", new OneToManyDisplayFunc());
            gt.registerFunction("oneToManyFuncValue", new OneToManyDisplayValueFunc());
            gt.registerFunction("projectTittleFunc", new ProjectTittleFunc());
            gt.registerFunction("oneToManyDictDisplayFunc", new OneToManyDictDisplayFunc());
            me.setRenderFactory(jFinal3BeetlRenderFactory);
//            gt.registerTag("dictTag", DictTag.class);
            /*gt.registerFunction("orderBy", new OrderBy());
            gt.registerFunction("escapeHtml", new EscapeHtml());
            gt.registerFunction("unEscapeHtml", new UnEscapeHtml());
            gt.registerFunction("i18nFormat", new I18nFormat());*/
            /*gt.registerTag("param", ParamTag.class);
            gt.registerFormat("dateFormat", new DateFormat());*/
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void configRoute(Routes me) {
        me.add(new AdminRoute());
        me.add("/api", IndexController.class);
        me.add("/wxpay", WxPayController.class);
    }

    @Override
    public void configEngine(Engine me) {
        //me.addSharedMethod()
        //me.addSharedFunction("/admin/common/data_table.html");
    }

    /**
     * mysql.driverClass = com.mysql.jdbc.Driver
     * #mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/news?characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull
     * mysql.jdbcUrl = jdbc:mysql://47.94.153.3:3306/news?autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull
     * mysql.userName = root
     * #mysql.passWord = 123456
     * mysql.passWord = bs5200.
     *
     * @param me
     */
    @Override
    public void configPlugin(Plugins me) {
        loadPropertyFile("init.properties");
        boolean isTest = getPropertyToBoolean("isTest");
//        暂时还是得分开的呀，静态页面以后要改咋么办呢  最新爆笑视频集
        String project_name = getProperty("project_name");
        String jdbcUrl1 = getProperty("jdbcUrl1");
        String jdbcUrl = jdbcUrl1 + project_name + "?autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull";
        String userName = "root";
        String password = getProperty("password");
        if (isTest) {
            String jdbcUrllocal = getProperty("jdbcUrllocal");
            jdbcUrl = jdbcUrllocal + project_name + "?autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull";
            userName = "root";
            password = "123456";
        } else {
//if(projectname.equals())qqxy.b3ad.cn
        }
        // 用于缓存news模块的redis服务
//        注，没有commons-pool.jar会报错的
//        RedisPlugin bbsRedis = new RedisPlugin(CacheUtils.CACHEUTILS, "localhost");
//        me.add(bbsRedis);
        me.add(new EhCachePlugin());

        /*C3p0Plugin c3p0Plugin = new C3p0Plugin(getProperty("mysql.jdbcUrl"), getProperty("mysql.userName"),
                getProperty("mysql.passWord"));*/
        C3p0Plugin c3p0Plugin = new C3p0Plugin(jdbcUrl, userName, password);
        c3p0Plugin.setMaxPoolSize(1);
        c3p0Plugin.setInitialPoolSize(1);
        me.add(c3p0Plugin);

        ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(c3p0Plugin);
//        打印的sql语句都是带？的意义有多大
//        这里用到了JFinal的链式方法链用，JFinal有大量的方法采用链式结构，例如Controller.setAttr(...).setAttr(...).render("index.html");，以及yourModel.set(...).set(...).update();这种方式可以减少代码量，让代码更整洁 :)
        activeRecordPlugin.setShowSql(getPropertyToBoolean("show_sql_flag"));
        _MappingKit.mapping(activeRecordPlugin);
        me.add(activeRecordPlugin);
        if (getPropertyToBoolean("is_generator_entity")) {
            try {
                // base model 所使用的包名
                String baseModelPkg = "com.kgd.news.entity.eb";
                // base model 文件保存路径
                String baseModelDir = "F:\\javaweb/" + project_name + "/src/com/kgd/news/entity/eb";
                // model 所使用的包名
                String modelPkg = "com.kgd.news.entity";
                // model 文件保存路径
                String modelDir = "F:\\javaweb/" + project_name + "/src/com/kgd/news/entity";
                c3p0Plugin.start();
                Generator gn = new Generator(c3p0Plugin.getDataSource(), baseModelPkg, baseModelDir, modelPkg,
                        modelDir);
                gn.generate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        QuartzPlugin quartzPlugin = new QuartzPlugin();
        JobBean job = new JobBean();
//        动态添加
//        job.setJobClass("com.kgd.news.utils.quartz.CheckSplitHbOutTime");
//        job.setCronExpression(FormaterCronExpression.formaterCronExpression(task.getStr("closingTime")));
//        job.setJobGroup("DakeTaskJob");
//        job.setJobDesc("DakeTaskJob_" + taskid);
        quartzPlugin.addJob(job);
        me.add(quartzPlugin);
//        1 QuartzPlugin quartzPlugin = new QuartzPlugin();
//        2         quartzPlugin.setJobs("system-quartz.properties");
//        3         me.add(quartzPlugin);

//        test();
    }

//    private void test() {
//        VideoHelper.transUriToValid("https://v.qq.com/x/page/f0505lwxwa7.html");
//    }

    @Override
    public void configInterceptor(Interceptors me) {

    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("basePath"));
        me.add(new PermissionHandler());
    }

}
